import type { App } from 'vue'
import type { RouteRecordName, RouteRecordRaw } from 'vue-router'
import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'
import { EnvConfig } from '@/config'
import { traverseTreeValues } from '@/utils'
import { createRouterGuard } from './guard'
import { routes } from './routes'

// 静态路由所有节点包含子节点name数组
const staticRouteNames = traverseTreeValues<RouteRecordRaw, RouteRecordName | undefined>(routes, (route) => route.name)

/**
 *  创建vue-router实例
 */
const router = createRouter({
  history: EnvConfig.getInstance().routerHistory === 'hash' ? createWebHashHistory(EnvConfig.getInstance().baseUrl) : createWebHistory(EnvConfig.getInstance().baseUrl),
  // 应该添加到路由的初始路由列表。
  routes,
  scrollBehavior: (to, _from, savedPosition) => {
    if (savedPosition) {
      return savedPosition
    }
    return to.hash ? { behavior: 'smooth', el: to.hash } : { left: 0, top: 0 }
  }
  // 是否应该禁止尾部斜杠。
  // strict: true,
})

/**
 * 初始化设置路由
 */
const setupRouter = (app: App) => {
  app.use(router)
  // 创建路由守卫
  createRouterGuard(router)
}

/**
 * 重置所有路由，如有指定白名单除外 退出登录时需要删除路由
 */
const resetRoutes = () => {
  const { getRoutes, hasRoute, removeRoute } = router
  const allRoutes = getRoutes()
  allRoutes.forEach(({ name }) => {
    // 存在于路由表且非白名单才需要删除
    if (name && !staticRouteNames.includes(name) && hasRoute(name)) {
      removeRoute(name)
    }
  })
}

export { resetRoutes, router, setupRouter }
